#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTcpSocket>
#include <QMessageBox>
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setWindowTitle("Tcp客户端");

    //创建套接字
    socket = new QTcpSocket(this);

    //连接服务器
    socket->connectToHost("127.0.0.1",9090);

    //处理服务器响应的槽函数
    connect(socket,&QTcpSocket::readyRead,this,[=](){
       QString response = socket->readAll();
       ui->listWidget->addItem("服务器响应 " + response);
    });

    //由于connectToHost雷同于Linux中的connect，属于非阻塞等待握手
    //因此需要在后续代码中判断是否握手成功
    bool ret = socket->waitForConnected();
    if(ret == false)
    {
        QMessageBox::critical(this,"连接服务器出错",socket->errorString());
        exit(1);
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_pushButton_clicked()
{
    QString sendor = ui->lineEdit->text();


    socket->write(sendor.toUtf8());
    ui->listWidget->addItem("客户端发送 " + sendor);

    ui->lineEdit->setText("");

}
